package com.sunrise.configuracoes.repositorio;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.sunrise.configuracoes.repositorio.iface.MetaDao;
import com.sunrise.generico.acesso.DaoService;
import com.sunrise.generico.entidade.Meta;
import com.sunrise.generico.visao.Filtro;

@Repository
public class MetaDaoImpl extends DaoService<Meta> implements MetaDao {

	public List<Meta> listarOrdenado() {
		List<Meta> list = listar(Meta.class);
		Collections.sort(list, new Comparator<Meta>() {

			@Override
			public int compare(Meta o1, Meta o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public List<Meta> search(Meta ex) {
		List<Meta> list = searchByExample(Meta.class, ex);
		Collections.sort(list, new Comparator<Meta>() {

			@Override
			public int compare(Meta o1, Meta o2) {
				return o1.getNome().compareTo(o2.getNome());
			}
		});
		return list;
	}

	public Meta getById(Long id) {
		return getById(id, Meta.class);
	}

	@Override
	public List<Meta> listarPorNome(String nome) {
		return null;
	}

	@Override
	public Meta buscarPorNome(String nome) {
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Meta> listarPorFiltro(Filtro filtro) {
		Criteria crit = getSession().createCriteria(Meta.class);

		if (filtro.getNome() != null) {
			crit.add(Restrictions.like("nome", filtro.getNome(), MatchMode.ANYWHERE));
		}
		
		if (filtro.getDataInicio() != null) {
			crit.add(Restrictions.ge("dataInicio", filtro.getDataInicio()));
		}

		if (filtro.getDataFim() != null) {
			crit.add(Restrictions.le("dataFim", filtro.getDataFim()));
		}
		
		if (filtro.getAtivo() != null) {
			crit.add(Restrictions.eq("ativo", filtro.getAtivo().getCodigo()));
		}
		
		crit.createAlias("filial", "fil");
		crit.add(Restrictions.eq("fil.id", filtro.getIdFilial()));

		if (filtro.getIdFilial() == null) {
			return new ArrayList<Meta>();
		}

		crit.addOrder(Order.desc("id"));
			
		return crit.list();
	}

}
